
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../my_colors.dart';

typedef _RefreshCallBack = void Function(bool isUp);

class MyRefreshView extends StatelessWidget {
  final MyRefreshViewController controller;
  final _RefreshCallBack refreshCallBack;
  final Widget child;
  final Color backgroundColor;
  final bool isAndroidHead ;

  const MyRefreshView(
      {super.key,
      required this.refreshCallBack,
      required this.child,
      required this.controller,
      this.backgroundColor = Colors.white,
      this.isAndroidHead = true});

  void callRefresh() {
    /// 触发刷新
    controller.callRefresh();
  }

  void callLoad() {
    /// 触发加载
    controller.callLoad();
  }

  void finishRefresh() {
    /// 完成刷新
    /// TaskState
    controller.finishRefresh(success: true);
  }

  void finishLoad(bool noMore) {
    /// 完成加载
    controller.finishLoad(success: true, noMore: noMore);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return EasyRefresh(
      controller: controller,
      enableControlFinishRefresh: true,
      enableControlFinishLoad: true,
      header: isAndroidHead
          ? MaterialHeader(
              backgroundColor: backgroundColor,
            )
          : BallPulseHeader(
              backgroundColor: Colors.white, color: MyColors.appColor),
      footer: BallPulseFooter(
          backgroundColor: Colors.white, color: MyColors.appColor),
      child: child,
      onRefresh: () async {
        refreshCallBack(true);
      },
      onLoad: () async {
        refreshCallBack(false);
      },
    );
  }
}

class MyRefreshViewController extends EasyRefreshController {
  void beginRef() {
    /// 触发刷新
    callRefresh();
  }
  /// 结束刷新
  void refreshEnd({int? page, int? maxPage}) {
    finishRefresh(success: true);
    if (page == null || maxPage == null) {
      finishLoad(success: true, noMore: false);
    } else if (page >= maxPage) {
      finishLoad(success: true, noMore: true);
    } else {
      finishLoad(success: true, noMore: false);
    }
  }

  void refreshNoMore(bool noMore) {
    finishRefresh(success: true);
    finishLoad(success: true, noMore: noMore);
  }
}
